package cn.itcast.web;

import cn.itcast.pojo.Template;
import cn.itcast.pojo.TemplateParam;
import cn.itcast.rabbitmq.RabbitmqListener;
import cn.itcast.util.CommonUtil;
import cn.itcast.util.MessageQueue;
import cn.itcast.util.TextUtils;
import cn.wxgzh.web.WxgzhController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author lyy
 * @Description TODO
 * @PACKAGE_NAME: cn.itcast.web
 * @ClassName ReceiveMQ
 * @Date 2020/7/2 9:27
 * @DAY_NAME_FULL: 星期四
 * @Version 1.0
 **/
@Component
public class ReceiveMQ extends RabbitmqListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    @Resource
    cn.itcast.mapper.gzhMapper gzhMapper;

    WxgzhController wxgzhController = new WxgzhController();

    @Bean
    public Queue QUEUE_USER_TEST(){return new Queue(MessageQueue.QUEUE_USER_TEST);}
    @RabbitListener(queues = MessageQueue.QUEUE_USER_TEST)
    public void sendTest(Message message, Channel channel){
        String body = messageToString(message);
        try {
            if(!TextUtils.isEmpty(body)){
                JSONObject object = JSON.parseObject(body);
                String msg = object.getString("msg");
                if(!TextUtils.isEmpty(msg)){
                    logger.info("接受到的RabbitMQ数据：{}",msg);
                    logger.info("发送消息成功啦！！！");
                }else{
                    logger.info("发送消息失败了！！！");
                }
            }
        }catch (Exception e){
            logger.error("发送消息失败，出现了异常{}",e);
        }
    }

    /**
     * 功能描述: <br>
     * 〈用户申请提现成功 通过微信通知用户〉
     * @Author: lyy
     * @Date: 2020/7/2 11:37
     * @Param: []
     * @Return: org.springframework.amqp.core.Queue
     */
    @Bean
    public Queue QUEUE_WITHDRAW_REMIND(){return new Queue(MessageQueue.QUEUE_WITHDRAW_REMIND);}
    @RabbitListener(queues = MessageQueue.QUEUE_WITHDRAW_REMIND)
    public void sendWithdrawRemind(Message message){
        String body = messageToString(message);
        try {
            if(!TextUtils.isEmpty(body)){
                JSONObject object = JSON.parseObject(body);
                String openId = object.getString("openId");
                String money = object.getString("money");
                if(openId!=null && money!=null){
                    String withdrawRemind = withdrawRemind(openId,money);
                    if(withdrawRemind!=null&&!TextUtils.isEmpty(withdrawRemind)){
                        logger.info("RabbitMQ执行用户申请提现消息发送成功啦！！！");
                    }else{
                        logger.info("RabbitMQ执行用户申请提现消息发送失败");
                    }
                }else {
                    logger.info("{}：参数为空了",openId);
                    logger.info("{}：参数为空了",money);
                    logger.info("消息发送失败！！！");
                }
            }else{
                logger.info("消息发送失败，body参数为空：{}",body);
            }
        }catch (Exception e){
            logger.error("发送消息失败，出现了异常{}",e);
        }
    }


    /**
     * 功能描述: <br>
     * 〈用户提现审核通过 到账通知〉
     * @Author: lyy
     * @Date: 2020/7/3 10:10
     * @Param: []
     * @Return: org.springframework.amqp.core.Queue
     */
    @Bean
    public Queue QUEUE_WITHDRAW_CASH(){return new Queue(MessageQueue.QUEUE_WITHDRAW_CASH);}
    @RabbitListener(queues = MessageQueue.QUEUE_WITHDRAW_CASH)
    public void sendWithdrawCash(Message message){
        String body = messageToString(message);
        try {
            if(!TextUtils.isEmpty(body)){
                JSONObject object = JSON.parseObject(body);
                String openId = object.getString("openId");
                String money = object.getString("money");
                if(openId!=null && money!=null){
                    String sendWithdrawCash = sendWithdrawCash(openId,money);
                    if(sendWithdrawCash!=null&&!TextUtils.isEmpty(sendWithdrawCash)){
                        logger.info("RabbitMQ执行用户申请提现到账消息发送成功啦！！！");
                    }else{
                        logger.info("RabbitMQ执行用户申请提现到账消息发送失败");
                    }
                }else {
                    logger.info("{}：参数为空了",openId);
                    logger.info("{}：参数为空了",money);
                    logger.info("消息发送失败！！！");
                }
            }else{
                logger.info("消息发送失败，body参数为空：{}",body);
            }
        }catch (Exception e){
            logger.error("发送消息失败，出现了异常{}",e);
        }
    }

    @Bean
    public Queue QUEUE_WITHDRAW_FAILURE(){return new Queue(MessageQueue.QUEUE_WITHDRAW_FAILURE);}
    @RabbitListener(queues = MessageQueue.QUEUE_WITHDRAW_FAILURE)
    public void sendWithdrawFailure(Message message){
        String body = messageToString(message);
        try {
            if(!TextUtils.isEmpty(body)){
                JSONObject object = JSON.parseObject(body);
                String openId = object.getString("openId");
                String money = object.getString("money");
                if(openId!=null && money!=null){
                    String sendWithdrawFailure = sendWithdrawFailure(openId,money);
                    if(sendWithdrawFailure!=null&&!TextUtils.isEmpty(sendWithdrawFailure)){
                        logger.info("RabbitMQ执行用户申请提现审核不通过消息发送成功啦！！！");
                    }else{
                        logger.info("RabbitMQ执行用户申请提现审核不通过消息发送失败");
                    }
                }else {
                    logger.info("{}：参数为空了",openId);
                    logger.info("{}：参数为空了",money);
                    logger.info("消息发送失败！！！");
                }
            }else{
                logger.info("消息发送失败，body参数为空：{}",body);
            }
        }catch (Exception e){
            logger.error("发送消息失败，出现了异常{}",e);
        }
    }

    //微信订阅消息 用户提现成功 等待到账通知模板
    public String withdrawRemind(String openId,String money){

        wxgzhController.getUserToken();
        wxgzhController.getToken();
        String userToken = gzhMapper.selectByPrimaryKey(3).getAccessToken();
        Template userTemplate=new Template();
        userTemplate.setTemplate_id("rhK5O1OrYdETKmZhhKPLExtHJwcZR3Q-FcOIVnxv0vM");
        userTemplate.setTouser(openId);
        userTemplate.setPage("pages/order/main");
        List<TemplateParam> userparas=new ArrayList<TemplateParam>();
        userparas.add(new TemplateParam("phrase1","审核中"));
        userparas.add(new TemplateParam("amount2",money+"元"));
        userparas.add(new TemplateParam("time3",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date().getTime())));
        userparas.add(new TemplateParam("thing4","预计1-3个工作日到账"));
        userTemplate.setTemplateParamList(userparas);
        String requestuserUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        requestuserUrl=requestuserUrl.replace("ACCESS_TOKEN", userToken);
        logger.info("用户申请提现模板信息：{}",userTemplate.toJSON());
        net.sf.json.JSONObject jsonuserResult= CommonUtil.httpsRequest(requestuserUrl, "POST", userTemplate.toJSON());
        if(jsonuserResult!=null){
            logger.info("{}",jsonuserResult);
            int errorCode=jsonuserResult.getInt("errcode");
            String errorMessage=jsonuserResult.getString("errmsg");
            if(errorCode==0){
                logger.info("提醒用户环保金申请成功，等待审核 Send Success");
            }else{
                logger.info("用户申请提现，订阅消息发送失败:{},{}",errorCode,errorMessage);
            }
            return "用户申请提现，订阅消息发送成功";
        }else {
            return null;
        }
    }

    //微信订阅消息 用户提现成功 提现到账通知模板
    public String sendWithdrawCash(String openId,String money){
        wxgzhController.getUserToken();
        wxgzhController.getToken();
        String userToken = gzhMapper.selectByPrimaryKey(3).getAccessToken();
        Template userTemplate=new Template();
        userTemplate.setTemplate_id("8fxX4pVAAOKNIHAG_zu7nHE1mOpa8ifYAbLPmVd-UF4");
        userTemplate.setTouser(openId);
        userTemplate.setPage("pages/order/main");
        List<TemplateParam> userparas=new ArrayList<TemplateParam>();
        userparas.add(new TemplateParam("amount1",money+"元"));
        userparas.add(new TemplateParam("phrase2","微信钱包"));
        userparas.add(new TemplateParam("time3",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date().getTime())));
        userparas.add(new TemplateParam("thing4","您提现的"+money+"元已提现至您的微信钱包"));
        userparas.add(new TemplateParam("thing5","大黄牛环保金提现"));
        userTemplate.setTemplateParamList(userparas);
        String requestuserUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        requestuserUrl=requestuserUrl.replace("ACCESS_TOKEN", userToken);
        logger.info("用户申请提现到账模板信息：{}",userTemplate.toJSON());
        net.sf.json.JSONObject jsonuserResult= CommonUtil.httpsRequest(requestuserUrl, "POST", userTemplate.toJSON());
        if(jsonuserResult!=null){
            logger.info("{}",jsonuserResult);
            int errorCode=jsonuserResult.getInt("errcode");
            String errorMessage=jsonuserResult.getString("errmsg");
            if(errorCode==0){
                logger.info("提醒用户环保金提现成功，提现到账 Send Success");
            }else{
                logger.info("用户申请提现到账，订阅消息发送失败:{},{}",errorCode,errorMessage);
            }
            return "用户申请提现到账，订阅消息发送成功";
        }else {
            return null;
        }
    }

    //微信订阅消息 用户提现失败 审核不通过通知模板
    public String sendWithdrawFailure(String openId,String money){
        wxgzhController.getUserToken();
        wxgzhController.getToken();
        String userToken = gzhMapper.selectByPrimaryKey(3).getAccessToken();
        Template userTemplate=new Template();
        userTemplate.setTemplate_id("krB8zWOckrWiITXZ3MmXjXrnJTpXizagnGjg1Fb35ww");
        userTemplate.setTouser(openId);
        userTemplate.setPage("pages/order/main");
        List<TemplateParam> userparas=new ArrayList<TemplateParam>();
        userparas.add(new TemplateParam("amount1",money+"元"));
        userparas.add(new TemplateParam("phrase2","审核不通过"));
        userparas.add(new TemplateParam("thing3","您的提现审核失败，如有问题请拨打客户电话"));
        userTemplate.setTemplateParamList(userparas);
        String requestuserUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        requestuserUrl=requestuserUrl.replace("ACCESS_TOKEN", userToken);
        logger.info("用户申请提现失败模板信息：{}",userTemplate.toJSON());
        net.sf.json.JSONObject jsonuserResult= CommonUtil.httpsRequest(requestuserUrl, "POST", userTemplate.toJSON());
        if(jsonuserResult!=null){
            logger.info("{}",jsonuserResult);
            int errorCode=jsonuserResult.getInt("errcode");
            String errorMessage=jsonuserResult.getString("errmsg");
            if(errorCode==0){
                logger.info("提醒用户环保金提现审核不通过，审核不通过 Send Success");
            }else{
                logger.info("用户申请提现审核不通过，订阅消息发送失败:{},{}",errorCode,errorMessage);
            }
            return "用户申请提现审核不通过，订阅消息发送成功";
        }else {
            return null;
        }
    }
}
